﻿using ExchangeClient.Abstractions;
using ExchangeClient.Abstractions.Model;
using Microsoft.Extensions.Logging;
using SyncService.Abstractions.Services;
using SyncService.Core.Model;
using System;
using System.Collections.Generic;
using System.Composition;
using System.Linq;
using System.Text;
using System.Text.Json.Nodes;
using System.Text.Json;
using System.Threading.Tasks;
using NPOI.POIFS.Crypt.Dsig;
using SyncService.Abstractions.Events;
using System.Security.AccessControl;
using Microsoft.Extensions.Caching.Memory;
using System.Reflection.Emit;
using SyncService.Common;

namespace SyncService.Core.Services
{
    [Export(typeof(ISyncService))]
    [ExportMetadata(YdConstants.ID, "zeroToInstorage")]
    public class ZeroInstorageService : AssetSyncServiceBase
    {
        protected override string NotifyGroupName => "";
        private ILogger<AssetInstorageService> _logger = null;
        private IMemoryCache? _cache = null;

        private bool IsNotPush = false;
        private Dictionary<string, string> SourceDic = new Dictionary<string, string>() { {"购入","1" }, { "自建", "2" }, { "租赁", "3" }, { "捐赠", "4" }, { "内部购入", "6" }, { "盘盈", "7" }, { "试用", "8" }, { "其他", "5" } };
        public ZeroInstorageService() : base(YdConstants.YIDEA, "Esb", "")
        {
        }
        protected override void InitializeContext()
        {
            base.InitializeContext();
            _logger = Resolver.Resolve<ILogger<AssetInstorageService>>();
            _cache = Resolver.Resolve<IMemoryCache>();
        }
        private Dictionary<string, string> companyData = new Dictionary<string, string>();
        private Dictionary<string, string> centerData = new Dictionary<string, string>();
        public override void ExecuteCore()
        {
            var data = (AssetSyncEvent)State!;
            try
            {
                _logger.LogInformation("开始处理0元列管转入库");
                //YideaClient
                Thread.Sleep(5000);
                var serialNo=data!.Data!["SerialNo"]!.ToString();
                if (serialNo.Substring(0, 3)== "ZER") {
                    
                    QueryParam queryParam = new QueryParam();
                    //var id = data.Data["operator"]["id"].ToString();
                    //var tempId = Guid.Empty;
                    //Guid.TryParse(id, out tempId);
                    //if (tempId != Guid.Empty)
                    //{
                    //    queryParam.FilterString = "relatedEmployeeId=" + data.Data["operator"]["id"].ToString();
                    //}
                    //else {
                    //    queryParam.FilterString = "id=" + data.Data["operator"]["id"].ToString();
                    //}
                    queryParam.FilterString = "relatedEmployeeId=" + data.Data["operator"]["id"].ToString();

                    List<User> users= YideaClient.GetUsers(queryParam).ToList();

                    string userId = "";
                    string userName = "";
                    if (users.Count > 0) {
                        userId = users[0].Id.ToString();
                        userName=users[0].Name.ToString();
                    }

                

                    AssetInStorage assetInStorage = new AssetInStorage();
                    assetInStorage.Status = 1;
                    var companyCodeValueField = ExtendFields.First(x => x.ObjectType == 0 && x.Name == "CompanyCode");
                    var companyIdValueField = ExtendFields.First(x => x.ObjectType == 0 && x.Name == "CompanyId");
                    var invoiceFiled = ExtendFields.First(x => x.ObjectType == 0 && x.Name == "发票号码"); 
                    var comapnyCodeFiled = ExtendFields.First(x => x.ObjectType == 0 && x.Name == "公司代码"); 
                        var centerCodeFiled = ExtendFields.First(x => x.ObjectType == 0 && x.Name == "成本中心码");
                    var applicationSerialNoFiled = ExtendFields.First(x => x.ObjectType == 0 && x.Name == "费控申请单号");
                    var applicationRowFiled = ExtendFields.First(x => x.ObjectType == 0 && x.Name == "费控申请行号");
                    var purchaseOrderFiled = ExtendFields.First(x => x.ObjectType == 0 && x.Name == "采购订单号");
                    var reciveFiled = ExtendFields.First(x => x.ObjectType == 0 && x.Name == "收货单号");
                    var companyNameField = ExtendFields.First(x => x.ObjectType == 0 && x.Name == "公司名称");
                    var companyNameInputField = ExtendFields.First(x => x.ObjectType == 0 && x.Name == "公司名");
                    var assetcenterNameField = ExtendFields.First(x => x.ObjectType == 0 && x.Name == "成本中心名称");
                    var assetcenterNameInputField = ExtendFields.First(x => x.ObjectType == 0 && x.Name == "成本中心名");
                    var assetBrandField = ExtendFields.First(x => x.ObjectType == 0 && x.Name == "品牌");
                    var assetOrigialField = ExtendFields.First(x => x.ObjectType == 0 && x.Name == "资产原值");
                    var assetMasterNetWorthField = ExtendFields.First(x => x.ObjectType == 0 && x.Name == "资产净值");
                    var assetMasterTopTypeField = ExtendFields.First(x => x.ObjectType == 0 && x.Name == "资产大类");
                    var assetMasterSourceFiled = ExtendFields.First(x => x.ObjectType == 0 && x.Name == "资产来源");
                    var assetAdressDaleiField = ExtendFields.First(x => x.ObjectType == 0 && x.Name == "存放地大类");
                    var assetShopCodeField = ExtendFields.First(x => x.ObjectType == 0 && x.Name == "店铺代码");
                    var assetShopNameField = ExtendFields.First(x => x.ObjectType == 0 && x.Name == "店铺名称");
                    var assetAdressField = ExtendFields.First(x => x.ObjectType == 0 && x.Name == "存放地");

                    var companyMasterCodeField = ExtendFields.First(x => x.ObjectType == 51 && x.Name == "公司代码");
                    var companyMasterNameField = ExtendFields.First(x => x.ObjectType == 51 && x.Name == "公司名称");

                    var centerCodeField = ExtendFields.First(x => x.ObjectType == 52 && x.Name == "成本中心");
                    var centerNameField = ExtendFields.First(x => x.ObjectType == 52 && x.Name == "成本中心名称");

                    var sourceField = ExtendFields.First(x => x.ObjectType == 57 && x.Name == "来源");
                    var assetListCodeField = ExtendFields.First(x => x.ObjectType == 57 && x.Name == "资产列表");

                    var isCarryToField = ExtendFields.First(x => x.ObjectType == 0 && x.Name == "是否过账");

                    var company=  UserDefines.First(x => x.Name == "公司主数据");
                    var center = UserDefines.First(x => x.Name == "成本中心");

                    #region 获取公司，成本中心,部门
                    var companyList = YideaClient.GetCustomizedFormDatas(formId: company.Id, new QueryParam() { }).ToList();
                    ConvertCompanyToDic(companyList);
                    var centerlist = YideaClient.GetCustomizedFormDatas(formId: center.Id, new QueryParam() { }).ToList();
                    ConvertCenterToDic(centerlist);

                    List<Department> departments= YideaClient.GetDepartments(null).ToList();
                    List<Company> companies=YideaClient.GetCompanies(null).ToList();
                    #endregion

                   var source = data.Data[sourceField.FieldId]["value"].ToString();
                    var mainform = new YideaMainFormAssetInStorage()
                    {
                        Date = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd 00:00:00")),
                        CreateDate = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd 00:00:00")),
                        Creator=new JsonObject
                        {
                            ["value"] =userId ,
                            ["label"] = userName
                        },
                        OwnCompany = new JsonObject
                        {
                            ["value"] = companyIdValueField.FieldId,//修改值
                            ["code"] = companyCodeValueField.FieldId,//修改值
                            ["label"] = "宝胜集团",
                            ["type"] = "departmentName"
                        },
                        Source = new JsonObject
                        {

                            ["value"] = SourceDic[source],
                            ["label"] = source,
                            ["color"] = new JsonObject
                            {
                                ["backgroundColor"] = "#577eff",
                                ["foreColor"] = "#ffffff"

                            },
                        },
                        ReceiptSerialNumber=serialNo,
                        ManualReceiptNumber="",
                        FlowFlag="3"
                    };
                    assetInStorage.FormJson = JsonSerializer.Serialize(mainform) ;
                    var assetList = new JsonArray();
                    var assetInStorageList=data!.Data![assetListCodeField.FieldId].AsArray();

                    var assetNameField = ExtendFields.First(x => x.ObjectType == 57 && x.Name == "资产名称");
                    var assetTypeCodeField = ExtendFields.First(x => x.ObjectType == 57 && x.Name == "资产分类");
                    var districeFiled = ExtendFields.First(x => x.ObjectType == 57 && x.Name == "区域");


                    var instorageCompanyCodeField = ExtendFields.First(x => x.ObjectType == 57 && x.Name == "公司代码");
                    var instorageCompanyNameField = ExtendFields.First(x => x.ObjectType == 57 && x.Name == "公司名称");
                    var instorageCenterCodeField = ExtendFields.First(x => x.ObjectType == 57 && x.Name == "成本中心代码");
                    var instorageCenterNameField = ExtendFields.First(x => x.ObjectType == 57 && x.Name == "成本中心名称");


                    var brandField = ExtendFields.First(x => x.ObjectType == 57 && x.Name == "品牌");
                    var specField = ExtendFields.First(x => x.ObjectType == 57 && x.Name == "规格型号");
                    var assetTopTypeField = ExtendFields.First(x => x.ObjectType == 57 && x.Name == "资产大类");
                    var shopCodeField = ExtendFields.First(x => x.ObjectType == 57 && x.Name == "店铺代码");
                    var shopNameField = ExtendFields.First(x => x.ObjectType == 57 && x.Name == "店铺名称");
                    var assetMasterSourceField = ExtendFields.First(x => x.ObjectType == 57 && x.Name == "资产来源");
                    var assetAddressField = ExtendFields.First(x => x.ObjectType == 57 && x.Name == "实际存放地");
                    var assetAmountField = ExtendFields.First(x => x.ObjectType == 57 && x.Name == "原值");
                    var assetNetWorthField = ExtendFields.First(x => x.ObjectType == 57 && x.Name == "净值");
                    var purchaseDateField = ExtendFields.First(x => x.ObjectType == 57 && x.Name == "购入日期");
                    var managerField = ExtendFields.First(x => x.ObjectType == 57 && x.Name == "管理人选择");
                    var useDepartmentField = ExtendFields.First(x => x.ObjectType == 57 && x.Name == "使用部门");
                    var useEmployeeField = ExtendFields.First(x => x.ObjectType == 57 && x.Name == "使用人"); 
                   var assetCountField = ExtendFields.First(x => x.ObjectType == 57 && x.Name == "资产数量");
                    foreach (var asset in assetInStorageList)
                    {
                        var assetTypeCode = asset[assetTypeCodeField.FieldId]["value"].ToString();
                        string count = asset[assetCountField.FieldId]?.ToString();
                        var assetCount = 1;
                        if (!string.IsNullOrEmpty(count)) {
                            assetCount = int.Parse(count);
                        }
                        var brand = asset[brandField.FieldId]?.ToString();

                        var spec = asset[specField.FieldId]?.ToString();

                        var assetTypeName = GetAssetTypeByCode(assetTypeCode);

                        JsonObject companyDetail = new JsonObject();
                        var instorageCompanyCode = data.Data[instorageCompanyCodeField.FieldId].ToString();

                        var instorageCompanyName = data.Data[instorageCompanyNameField.FieldId].ToString();
                        //var companyData = YideaClient.GetCustomizedFormDatas(formId: company.Id, new QueryParam()
                        //{
                        //    FilterString = "[{\"field\":\"" + companyMasterCodeField.FieldId + "\",\"type\":\"input\",\"label\":\"公司代码\",\"opt\":\"Equal\",\"val\":\"" + instorageCompanyCode + "\"}]"
                        //}).ToList();
                        var companyJson = "";
                        companyData.TryGetValue(instorageCompanyCode, out companyJson);

                        if (!string.IsNullOrEmpty(companyJson))
                        {
                            companyDetail = JsonNode.Parse(companyJson).AsObject();
                            companyDetail.Remove("dataJson");
                            companyDetail[companyMasterCodeField.FieldId] = instorageCompanyCode;
                            instorageCompanyName = instorageCompanyName;
                            companyDetail[companyMasterNameField.FieldId] = instorageCompanyName;
                        }

                        JsonObject centerDetail = new JsonObject();
                        var instorageCenterCode = asset[instorageCenterCodeField.FieldId].ToString();
                        var instorageCenterName = asset[instorageCenterNameField.FieldId].ToString();
                        //var centerData = YideaClient.GetCustomizedFormDatas(formId: center.Id, new QueryParam()
                        //{
                        //    FilterString = "[{\"field\":\"" + centerCodeField.FieldId + "\",\"type\":\"input\",\"label\":\"成本中心\",\"opt\":\"Equal\",\"val\":\"" + instorageCenterCode + "\"}]"
                        //}).ToList();
                        var centerJson = "";
                        centerData.TryGetValue(instorageCenterCode, out centerJson);
                        if (!string.IsNullOrEmpty(centerJson))
                        {
                            centerDetail = JsonNode.Parse(centerJson).AsObject();
                            centerDetail.Remove("dataJson");
                            centerDetail[centerCodeField.FieldId] = instorageCenterCode;
                            centerDetail[centerNameField.FieldId] = instorageCenterName;
                        }
                        //店铺，存放地
                        string shopCode = "", shopDataJson = "\"\"", shopCodeValue="";
                        if (asset[shopCodeField.FieldId] != null && asset[shopCodeField.FieldId].ToString() != "" && asset[shopCodeField.FieldId].ToString() != "{}")
                        {
                            shopCode = asset[shopCodeField.FieldId]?["label"].ToString();
                            shopCodeValue = asset[shopCodeField.FieldId]?["value"].ToString();
                            shopDataJson = "{\"id\":\"" + shopCodeValue + "\",\"value\":\"" + shopCodeValue + "\",\"label\":\"" + shopCode + "\"}";
                        }
                        var assetTopType = asset[assetTopTypeField.FieldId]["value"].ToString();


                        var name = asset[assetNameField.FieldId].ToString();
                        var shopname = asset[shopNameField.FieldId]?.ToString();

                        var assetdistrictName = asset[districeFiled.FieldId]["label"].ToString();
                        var assetMasterSource = data.Data[assetMasterSourceField.FieldId]["value"].ToString();
                        var assetAdress = asset[assetAddressField.FieldId].ToString();
                        var assetAmount = asset[assetAmountField.FieldId]?.ToString();
                        var assetNetWorth = asset[assetNetWorthField.FieldId]?.ToString();

                        string useDepartmentCode = "", useDepartmentName = "";
                        string useEmployeeCode = "", useEmployeeName = "";
                        string useCompanyCode = "", useCompanyName = "";
                        if (asset[useDepartmentField.FieldId] != null)
                        {
                            useDepartmentCode = asset[useDepartmentField.FieldId]["code"].ToString();
                            useDepartmentName = asset[useDepartmentField.FieldId]["label"].ToString();
                            Department department = departments.Where(e => e.Code == useDepartmentCode).FirstOrDefault(); // YideaClient.GetDepartment(useDepartmentCode);
                            if (department != null)
                            {
                                var companyData = companies.Where(e => e.Code == department.CompanyCode).FirstOrDefault();
                                if (companyData!=null)
                                {
                                    useCompanyCode = department.CompanyCode;
                                    useCompanyName = companyData.Name;

                                }
                                //var usecompany = YideaClient.GetCompany(department.CompanyCode);
                                //if (usecompany != null)
                                //{
                                //    useCompanyCode = department.CompanyCode;
                                //    useCompanyName = usecompany.Name;
                                //}
                            }
                        }
                        if (asset[useEmployeeField.FieldId] != null)
                        {
                            useEmployeeCode = asset[useEmployeeField.FieldId]["code"].ToString();
                            useEmployeeName = asset[useEmployeeField.FieldId]["label"].ToString();
                        }
                        for (int i = 0; i < assetCount; i++)
                        {
                            assetList.Add(new JsonObject
                            {
                                ["user"] = useEmployeeName,
                                ["userEmployeeNo"] = useEmployeeCode,
                                ["useCompanyName"] = useCompanyName,
                                ["useDepartmentName"] = useDepartmentName,
                                ["useDepartmentCode"] = useDepartmentCode,
                                ["name"] = name,
                                ["specs"] = spec,
                                ["EXT_" + assetBrandField.FieldId] = brand,
                                ["EXT_" + isCarryToField.FieldId] = "是",
                                ["assetTypeName"] = assetTypeName,
                                ["districtName"] = assetdistrictName,
                                ["supervisor"] = asset[managerField.FieldId]["label"].ToString(),
                                ["supervisorNo"] = asset[managerField.FieldId]["code"].ToString(),
                                ["purchaseDate"] = CommonTimeStamp.GetDateTimeSeconds(long.Parse(asset[purchaseDateField.FieldId].ToString())).ToString("yyyy-MM-dd"),
                                ["amount"] = assetAmount,
                                ["EXT_" + assetMasterTopTypeField.FieldId + "_VALUE"] = assetTopType,
                                //["EXT_" + assetAdressDaleiField.FieldId + "_VALUE"] = adressDalei,
                                ["EXT_" + assetShopCodeField.FieldId + "_VALUE"] = shopCode,
                                ["EXT_" + assetOrigialField.FieldId + "_VALUE"] = assetAmount,
                                ["EXT_" + assetMasterNetWorthField.FieldId + "_VALUE"] = assetNetWorth,
                                ["EXT_" + assetMasterTopTypeField.FieldId] = new JsonObject
                                {
                                    ["value"] = assetTopType,
                                    ["label"] = assetTopType,
                                    ["color"] = new JsonObject
                                    {
                                        ["backgroundColor"] = "#52a8ff",
                                        ["foreColor"] = "#ffffff"
                                    }
                                },
                                ["EXT_" + assetMasterSourceFiled.FieldId + "_VALUE"] = assetMasterSource,
                                ["EXT_" + assetMasterSourceFiled.FieldId] = new JsonObject
                                {
                                    ["value"] = assetMasterSource,
                                    ["label"] = assetMasterSource,
                                    ["color"] = new JsonObject
                                    {
                                        ["backgroundColor"] = "#4fbbe0",
                                        ["foreColor"] = "#ffffff"
                                    }
                                },
                                ["EXT_" + assetShopNameField.FieldId] = shopname,
                                ["EXT_" + assetAdressField.FieldId] = assetAdress,
                                ["EXT_" + invoiceFiled.FieldId] = "0",
                                ["EXT_" + comapnyCodeFiled.FieldId] = instorageCompanyCode,
                                ["EXT_" + assetcenterNameInputField.FieldId] = instorageCenterName,
                                ["EXT_" + companyNameInputField.FieldId] = instorageCompanyName,
                                ["EXT_" + centerCodeFiled.FieldId] = instorageCenterCode,
                                //["EXT_" + applicationSerialNoFiled.FieldId] = applicationSerialNo,
                                //["EXT_" + applicationRowFiled.FieldId] = applicationRow,
                                //["EXT_" + purchaseOrderFiled.FieldId] = purchaseOrder,
                                ["EXT_" + reciveFiled.FieldId] = serialNo,
                                ["dataJson"] = "{\"" + isCarryToField.FieldId + "\":\"是\",\"" + assetMasterNetWorthField.FieldId + "\":\"" + assetNetWorth + "\",\"" + assetOrigialField.FieldId + "\":\"" + assetAmount + "\",\"" + assetShopCodeField.FieldId + "\":" + shopDataJson + ",\"" + assetAdressField.FieldId + "\":\"" + assetAdress + "\",\"" + assetShopNameField.FieldId + "\":\"" + shopname + "\",\"" + assetMasterTopTypeField.FieldId + "\":{\"value\":\"" + assetTopType + "\",\"label\":\"" + assetTopType + "\",\"color\":{\"backgroundColor\":\"#52a8ff\",\"foreColor\":\"#ffffff\"}},\"" + assetMasterSourceFiled.FieldId + "\":{\"value\":\"" + assetMasterSource + "\",\"label\":\"" + assetMasterSource + "\",\"color\":{\"backgroundColor\":\"#4fbbe0\",\"foreColor\":\"#ffffff\"}},\"" + assetBrandField.FieldId + "\":\"" + brand + "\",\"" + invoiceFiled.FieldId + "\":\"0\",\"" + companyNameField.FieldId + "\":" + companyDetail + ",\"" + assetcenterNameField.FieldId + "\":" + centerDetail + ",\"" + comapnyCodeFiled.FieldId + "\":\"" + instorageCompanyCode + "\",\"" + companyNameInputField.FieldId + "\":\"" + instorageCompanyName + "\",\"" + centerCodeFiled.FieldId + "\":\"" + instorageCenterCode + "\",\"" + assetcenterNameInputField.FieldId + "\":\"" + instorageCenterName + "\",\"" + reciveFiled.FieldId + "\":\"" + serialNo + "\",\"version\":\"\"}",

                                //["vendor"] = assetVendor
                            });
                        }
                    }
                    _logger.LogInformation("0元列管转入库资产列表："+JsonSerializer.Serialize(assetList));
                    _logger.LogInformation("0元列管转入库资产formjson：" + JsonSerializer.Serialize(mainform));
                    assetInStorage.AssetList = assetList;
                    JsonObject ret = YideaClient.AddAssetInStorage(assetInStorage);
                    var instorageSerialNo = ret["serialNo"].ToString();
                    //UpdateZeroSerialNo(serialNo,instorageSerialNo);
                    _logger.LogInformation("0元列管转入库处理结果" + ret);
                }

                _logger.LogInformation("结束处理0元列管转入库");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "处理0元列管转入库异常");
            }

        }
        private void ConvertCompanyToDic(List<CustomizedFormData> datas)
        {
            var companyMasterCodeField = ExtendFields.First(x => x.ObjectType == 51 && x.Name == "公司代码");
            foreach (var data in datas)
            {
                var custmerData = JsonSerializer.Serialize(data.Data);
                JsonObject companyDataJson = JsonNode.Parse(data.Data["dataJson"].ToString()).AsObject();
                var key = companyDataJson[companyMasterCodeField.FieldId].ToString();
                if (companyData.ContainsKey(key))
                {
                    continue;
                }
                else
                {
                    companyData.Add(key, custmerData);
                }
            }
        }
        private void ConvertCenterToDic(List<CustomizedFormData> datas)
        {
            var centerMasterCodeField = ExtendFields.First(x => x.ObjectType == 52 && x.Name == "成本中心");
            foreach (var data in datas)
            {
                var custmerData = JsonSerializer.Serialize(data.Data);
                JsonObject companyDataJson = JsonNode.Parse(data.Data["dataJson"].ToString()).AsObject();
                var key = companyDataJson[centerMasterCodeField.FieldId].ToString();
                if (centerData.ContainsKey(key))
                {
                    continue;
                }
                else
                {
                    centerData.Add(key, custmerData);
                }
            }
        }
        private void UpdateZeroSerialNo(string serialNo,string instorageSerialNo) {

            var form = UserDefines.First(x => x.Name == "0元列管入库单");
            CustomizedFormData customizedFormData1 = new CustomizedFormData();
            customizedFormData1.FormId = form!.Id;
            customizedFormData1.WebhookPush = false;
            customizedFormData1.SerialNo = serialNo;
            JsonObject customizedData1 = new JsonObject();
            var pushStateField = ExtendFields.First(x => x.ObjectType == 57 && x.Name == "入库单号");
            JsonObject stateValue = new JsonObject();
            stateValue.Add("value", instorageSerialNo);
            customizedData1.Add(pushStateField.FieldId, stateValue);
       
            customizedFormData1.Data = customizedData1;
            var updateResponse1 = YideaClient.UpdateCustomizedFormData(customizedFormData1, null);
            _logger.LogInformation("更新0元列管入库单号结果：" + updateResponse1);

        }
        private List<AssetType> GetAssetTypeFromCache()
        {
            _cache.TryGetValue("AssetType", out var assetValue);
            List<AssetType> assetTypeList = new List<AssetType>();
            if (assetValue != null)
            {
                assetTypeList = ((IEnumerable<dynamic>)assetValue).Select(item => new AssetType
                {
                    Id = item.Id,
                    Name = item.Name,
                    Hierarchy = item.Hierarchy,
                    Code = item.Code
                }).ToList();
            }
            else
            {
                assetTypeList = FromClient.GetAssetTypes(null).ToList();
                _cache.Set("AssetType", assetTypeList, DateTime.Now.AddMinutes(5));
            }
            return assetTypeList;
        }
        protected string GetAssetTypeByCode(string assetTypeCode)
        {

            List<AssetType> assetTypeList = GetAssetTypeFromCache();
            
            var assetType = assetTypeList.Where(e => e.Code == assetTypeCode).FirstOrDefault();
            var hierarchy = assetType.Hierarchy.Split('|');
            string hierarchyName = "";
            foreach (var item in hierarchy) {
                if (!string.IsNullOrEmpty(item)) {
                    var topAssetType = assetTypeList.Where(e => e.Id == int.Parse(item)).FirstOrDefault();
                    if (topAssetType != null) {
                        hierarchyName+= topAssetType.Name+"/";
                    }
                }
            }
            if (!string.IsNullOrEmpty(hierarchyName)) {
                hierarchyName = hierarchyName.Substring(0, hierarchyName.Length - 1);
            }
            return hierarchyName;

        }
    }
}
